<?php 
//RabbitMQ 测试demo - 消费者

//配置信息 
$conn_args = array( 
    'host' => '127.0.0.1',  
    'port' => '5672',  
    'login' => 'guest',  
    'password' => 'guest', 
    'vhost'=>'/' 
);   
$e_name = 'e_linvo'; //交换机名 
$q_name = 'q_linvo'; //队列名 
$k_route = 'key_1'; //路由key 
 
//创建连接和channel 
$conn = new AMQPConnection($conn_args);   
if (!$conn->connect()) {   
    die("Cannot connect to the broker!\n");   
}   
$channel = new AMQPChannel($conn);   
 
//创建交换机    
$ex = new AMQPExchange($channel);   
$ex->setName($e_name); 
$ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型  AMQP_EX_TYPE_DIRECT AMQP_EX_TYPE_FANOUT AMQP_EX_TYPE_HEADERS AMQP_EX_TYPE_TOPIC  fanout > direct >> topic 比例大约为11：10：6
$ex->setFlags(AMQP_DURABLE); //持久化  可选AMQP_DURABLE AMQP_PASSIVE AMQP_AUTODELETE
echo "Exchange Status:".$ex->declareExchange().PHP_EOL;   
   
//创建队列    
$q = new AMQPQueue($channel); 
$q->setName($q_name);   
$q->setFlags(AMQP_DURABLE); //持久化  可选AMQP_DURABLE  AMQP_PASSIVE AMQP_EXCLUSIVE  AMQP_AUTODELETE
echo "Message Total:".$q->declareQueue().PHP_EOL;   
 
//绑定交换机与队列，并指定路由键 
echo 'Queue Bind: '.$q->bind($e_name, $k_route).PHP_EOL; 
 
//阻塞模式接收消息  阻塞的，无消息时会被挂起，适合循环中使用
echo "Message:\n";   
while(True){ 
    // $q->consume('processMessage');   
    $q->consume('processMessage', AMQP_AUTOACK); //自动ACK应答  
}  

//非阻塞的，取消息时有则取，无则返回false
// $msg = $q->get(AMQP_AUTOACK);
// echo $msg?$msg->getBody().PHP_EOL:'no msg';  
 

$conn->disconnect(); 
/**
 * 消费回调函数
 * 处理消息
 */ 
function processMessage($envelope, $queue) { 
    $msg = $envelope->getBody(); 
    echo $msg.PHP_EOL; //处理消息  
    // $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答 
}
?>